package com.czh.intelligentoj.judge;

import cn.hutool.json.JSONUtil;
import com.czh.intelligentoj.common.ErrorCode;
import com.czh.intelligentoj.exception.BusinessException;
import com.czh.intelligentoj.judge.codesandbox.CodeSandbox;
import com.czh.intelligentoj.judge.codesandbox.CodeSandboxFactory;
import com.czh.intelligentoj.judge.codesandbox.CodeSandboxProxy;
import com.czh.intelligentoj.judge.codesandbox.model.ExecuteCodeRequest;
import com.czh.intelligentoj.judge.codesandbox.model.ExecuteCodeResponse;
import com.czh.intelligentoj.judge.strategy.JudgeContext;
import com.czh.intelligentoj.model.dto.question.JudgeCase;
import com.czh.intelligentoj.judge.codesandbox.model.JudgeInfo;
import com.czh.intelligentoj.model.entity.Question;
import com.czh.intelligentoj.model.entity.QuestionSubmit;
import com.czh.intelligentoj.model.enums.QuestionSubmitStatusEnum;
import com.czh.intelligentoj.service.QuestionService;
import com.czh.intelligentoj.service.QuestionSubmitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/*
 * ClassName: JudgeServiceImpl
 * Package: com.czh.intelligentoj.judge
 * Description:
 *              判题服务实现类
 *              实现步骤：
 *               1、根据传入的题目提交ID查询题目提交记录
 *               2、如果题目提交状态不是“等待中”，就抛出异常，防止重复执行
 *               3、更新题目提交状态为判题中, 防止重复判题
 *               4、调用代码沙箱进行判题，获取判题结果
 *               5、根据输出结果来判断是否通过判题
 * @Author: CZH
 * @Create: 2025
 */
@Slf4j
public class JudgeServiceImpl implements JudgeService {
    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Value("${judge.type:remote}")
    private String type;

    @Resource
    private JudgeManager judgeManager;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        // 1、根据传入的题目提交ID查询题目提交记录
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null) {
            throw  new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目提交不存在");
        }
        // 根据提交记录的题目ID查询对应的题目信息
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        // 2、如果题目提交状态不是“等待中”，就抛出异常，防止重复执行
        if(questionSubmit.getTitleStatus() != QuestionSubmitStatusEnum.WATTING.getValue()){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判題中");
        }
        // 3、更新题目提交状态为判题中, 防止重复判题
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setTitleStatus(QuestionSubmitStatusEnum.RUNNINTG.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "判题状态更新错误");
        }
        //4、调用代码沙箱进行判题，获取判题结果
        //构建代码沙箱实例
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        //使用代理装饰代码沙箱实例，便于后续扩展功能
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        //获取用户提交的代码、题目判题案例、编程语言
        String titleCode = questionSubmit.getTitleCode();
        String judgeCase = question.getJudgeCase();
        String language = questionSubmit.getProLanguage();
        //将题目判题案例转换为输入列表
        List<JudgeCase> list = JSONUtil.toList(judgeCase, JudgeCase.class);
        List<String> inputList = list.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        //构建判题请求
        ExecuteCodeRequest build = ExecuteCodeRequest.builder()
                .code(titleCode)
                .inputList(inputList)
                .language(language)
                .build();
        //执行判题
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(build);
        //5、根据输出结果来判断是否通过判题
        //获取输出结果，并与题目判题案例的输出进行对比
        List<String> outputList = executeCodeResponse.getOutput();
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputtList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(list);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        //6、修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setTitleStatus(QuestionSubmitStatusEnum.RUNNINTG.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "判题状态更新错误");
        }
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionId);
        return questionSubmitResult;
    }
}
